﻿
using MicroTest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace HttpHelper
{

    public class UploadInfo
    {
        public int ErrorCode = -1;
        public string ErrMsg = string.Empty;
    }
    public class UploadPackageInfo
    {
        public string Title = string.Empty;
        public string FilePath = string.Empty;
    }
    
    public class NetCommunication
    {

        private static string GetPlatformURL()
        {
            //return "http://192.168.20.69:8018/api/image/Post?type=ht";

#if DEBUG
            return "http://192.168.20.69:8018/api/image/Post?type=ht";
#else
            return "http://51ceping.net:82/api/image/Post?type=ht";
#endif

        }
        private static string GetPlatformDownLoadURL()
        {
            //return "http://192.168.20.69:8018/api/image/";

#if DEBUG
            return "http://192.168.20.69:8018/api/image/";
#else
            return "http://www.51ceping.net:82/api/image/";
#endif

        }
        private static string GetPlatformForLogin()
        {
            //return "http://192.168.20.69:8018/weice/";

#if DEBUG
            return "http://192.168.20.69:8018/weice/";
#else
            return "http://51ceping.net:82/weice/";
#endif
        }
        
        public bool NetGetRequest(string queryString,ref string msg)
        {
            string url= GetPlatformForLogin() + queryString;
#if DEBUG
            ELogger.Trace(url);
#endif
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            bool bSuccess = false;
            try
            {
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader streamReader = new StreamReader(res.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();
                res.Close();
                streamReader.Close();
                msg = responseContent;
                bSuccess = true;

            }
            catch (Exception ex)
            {
                bSuccess = false;
                msg = ex.Message;
            }
            return bSuccess;
            
        }
        public bool NetDownLoadRequest(string queryString,string fn, ref string msg)
        {
            string url =GetPlatformDownLoadURL() + queryString;
#if DEBUG
            ELogger.Trace(url);
#endif
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            bool bSuccess = false;
            try
            {
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                int length = (int)res.ContentLength;
                MemoryStream memoryStream = new MemoryStream();
                byte[] buffer = new byte[0x100];
                Stream rs = res.GetResponseStream();
                int total = 0;
                for (int i = rs.Read(buffer, 0, buffer.Length); i > 0; i = rs.Read(buffer, 0, buffer.Length))
                {
                    memoryStream.Write(buffer, 0, i);
                    total += i;
                }
                rs.Close();
                byte[] data = memoryStream.ToArray();
                using (BinaryWriter writer = new BinaryWriter(new FileStream(fn, FileMode.OpenOrCreate, FileAccess.Write)))
                {
                    writer.Write(data);
                }
                memoryStream.Close();


                bSuccess = true;

            }
            catch (Exception ex)
            {
                bSuccess = false;
                msg = ex.Message;
            }
            return bSuccess;

        }
        
        public  UploadInfo PostMicrotestData(string videoInfo,string url)
        {
            HttpClient httpClient = new HttpClient();
            httpClient.Url = GetPlatformURL();
            string sign = string.Empty;// SignRSA(videoInfo.Title);
            
            HttpUploadingFile file = new HttpUploadingFile(videoInfo, "file");
            httpClient.Files.Add(file);
            string msg = string.Empty;
            
            string respondStr = httpClient.GetStringWithMsg(Encoding.UTF8,ref msg);
            if(respondStr==null)
            {
                ELogger.Trace("null "+msg);
                UploadInfo info = new UploadInfo();
                info.ErrorCode = -1;
                info.ErrMsg = msg;
                return info;
            }
            if (respondStr != null && respondStr.Length > 0)
            {
                ELogger.Trace(string.Format("接口返回参数：{0}",respondStr));
                UploadInfo upinfo = new UploadInfo();
                if (respondStr.IndexOf("state:0") != -1)
                {
                    upinfo.ErrorCode = 0;
                }
                else
                    upinfo.ErrorCode = 1;
                upinfo.ErrMsg = respondStr;
                ELogger.Trace(respondStr);
                return upinfo;
            }
            return null;
        }
        public event  EventHandler<StatusUpdateEventArgs> UploadStatus;
        void httpClient_UploadStatus(object sender, StatusUpdateEventArgs e)
        {
            if (UploadStatus != null)
                UploadStatus(sender, e);
        }

        

        public static string GetMD5(string s)
        {
            string sMD5 = string.Empty;

            MD5CryptoServiceProvider md5CSP = new MD5CryptoServiceProvider();
            //获取要加密的字段，并转化为Byte[]数组  
            byte[] testEncrypt = System.Text.Encoding.UTF8.GetBytes(s);
            //加密Byte[]数组  
            byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt);
            foreach (byte InByte in resultEncrypt)
            {
                sMD5 = (sMD5 + String.Format("{0:x2} ", InByte)).Trim();
            }
            return sMD5;
        }

        internal static byte[] GetMD5Bytes(string s)
        {
            string sMD5 = string.Empty;

            MD5CryptoServiceProvider md5CSP = new MD5CryptoServiceProvider();
            //获取要加密的字段，并转化为Byte[]数组  
            byte[] testEncrypt = System.Text.Encoding.UTF8.GetBytes(s);
            //加密Byte[]数组  
            byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt);
            return resultEncrypt;
        }

        /// <summary>
        /// MD5 16位加密 加密后密码为大写
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        internal static string GetMd5Str(string ConvertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }

       
    }
}
